package cn.dansj.handler.interfaces;

import cn.dansj.annotation.InterfaceParam;
import cn.dansj.annotation.MarkAsApi;
import cn.dansj.bean.FileUploadInfo;
import cn.dansj.common.utils.bean.ResponseMessage;
import cn.dansj.common.utils.enums.ResponseCode;
import cn.dansj.common.utils.json.DictMap;
import cn.dansj.common.utils.transfer.GetTime;
import cn.dansj.common.utils.transfer.Md5Utils;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.exception.InterfaceResponseException;
import cn.dansj.handler.InterfaceHandler;
import cn.dansj.utils.project.ProjectUtils;
import com.alibaba.fastjson2.JSONObject;
import io.minio.StatObjectResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@MarkAsApi
public class EdgeUpload extends InterfaceHandler {
    private static final String insert = "insert into x_edge_component(id,component,height,width,url) values(?,?,?,?,?)";
    private static final String delete = "delete from x_edge_component where id=?";
    private static final String sign = "sja4d8ijs2adc1nmd2xc";

    @Override
    @InterfaceParam(value = "file", require = true, comment = "上传的文件")
    public Object execute(Map<String, Object> paramsMap) {
        try {
            String md5 = upload((MultipartFile) paramsMap.get("file"));
            redisUtils.set("verificationCode@sign", sign);
            String url = "https://dmp.dansj.cn/file/get/edge/" + md5 + "?sign=" + sign + "&preview&cache";
            if (Transformation.castToBoolean(paramsMap.get("picture"))) {
                jdbcTemplate.update(delete, md5);
                String[] splitResolution = Transformation.toString(paramsMap.get("resolution")).split("x");
                jdbcTemplate.update(insert, md5, "picture", splitResolution[1], splitResolution[0], url);
            }
            return url;
        } catch (Exception e) {
            throw new InterfaceResponseException(ResponseCode.Error.getStatusCode(), e.getMessage());
        }
    }

    public String upload(MultipartFile file) throws IOException {
        String bucket = "edge";
        String md5 = Md5Utils.md5(file.getBytes());
        final String defaultBucket = ProjectUtils.getSettingByRedis("minio", "defaultBucket", "project");
        StatObjectResponse fileInfo = ProjectUtils.getMinio().fileInfo(defaultBucket, md5);

        if (fileInfo != null) {
            //存在文件，直接写入记录到redis
            return saveUploadFileInfo(new FileUploadInfo().setFileMd5(md5).setFileName(md5).setBucketName(bucket).setFileSize(fileInfo.size()));
        } else {
            //正常上传
            final ResponseMessage responseMessage = ProjectUtils.getMinio().upload(defaultBucket, file, md5);
            if (responseMessage.getStatus()) {
                return saveUploadFileInfo(new FileUploadInfo().setFileMd5(md5).setFileName(md5).setBucketName(bucket).setFileSize(file.getSize()));
            }
            return null;
        }
    }

    public String saveUploadFileInfo(FileUploadInfo fileUploadInfo) {
        //存入数据库
        final JSONObject minioFile = new JSONObject();
        String fileMd5 = fileUploadInfo.getFileMd5();
        minioFile.put("id", fileMd5);
        minioFile.put("createTime", GetTime.dbTimestamp());
        minioFile.put("bucketName", fileUploadInfo.getBucketName());
        minioFile.put("fileSize", fileUploadInfo.getFileSize());
        minioFile.put("fileMd5", fileMd5);
        minioFile.put("fileName", fileUploadInfo.getFileName());
        final JSONObject obj = DictMap.from(redisUtils.hgetall(ProjectUtils.getBucketName(fileUploadInfo.getBucketName())));
        final JSONObject files = obj.getJSONObject("files");
        files.put(fileMd5, minioFile);
        obj.put("files", files);
        redisUtils.hmset(ProjectUtils.getBucketName(fileUploadInfo.getBucketName()), obj);
        return fileMd5;
    }
}
